<template>
  <el-form :model="dataForm" :rules="rules" label-position="top" class="form-box" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
    label-width="120px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="dataForm.title" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="author" label="作者">
          <el-input v-model="dataForm.author" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="cover" label="封面图">
          <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image class="avatar" v-if="dataForm.cover" :src="dataForm.cover" :zoom-rate="1.2" :max-scale="7"
              :min-scale="0.2" :preview-src-list="[dataForm.cover]" show-progress fit="cover" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item prop="content" label="公告内容">
      <wang-editor v-model="dataForm.content" mode="simple"></wang-editor>
    </el-form-item>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, UploadProps } from "element-plus";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import WangEditor from '@/components/wang-editor/index.vue';
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const url = ref("");

const dataForm = reactive({
  id: "",
  title: "",
  author: "",
  cover: "",
  coverId: null,
  content: "",
});

const rules = ref({
  title: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  author: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  cover: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  content: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
});

const init = (id?: string) => {
  visible.value = true;
  url.value = `${app.api}/sys/oss/upload?token=${getToken()}`;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (route.query?.id) {
    getInfo(`${route.query?.id}`);
  }
};

// 获取信息
const getInfo = (id: string) => {
  baseService.get(`/study/notice/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  dataForm.cover = response?.data?.src;
  dataForm.coverId = response?.data?.id;
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('图片格式不支持!')
    return false
  }
  return true
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)('/study/notice', dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
          router.push('/study/notice');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 100%;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar-uploader {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 120px;
  text-align: center;
}
</style>
